<?php

namespace App\Http\Controllers;
use Carbon\Carbon;

use App\Http\Service\Douban\DoubanpostService;
use App\Http\Service\WeiboService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Http\Service\PythonService;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
#浏览历史记录
class WeiboController extends BaseController
{
    private $getRules=[
            'unique_id'=> 'required',
        ];
    private  $getRulesMessage=[
            'unique_id.required'=> '唯一标识【unique_id】不能为空',
        ];

    public $repository;

    public function __construct(WeiboService $repository,PythonService $pythonService)
    {
        parent::__construct();
        $this->repository = $repository;
        $this->pythonService=$pythonService;

    }
    public function extractQuotesAndText($text) {
        // 提取所有引用内容
        preg_match_all('/\[引用内容\]:\s*(.+?)(?=\s*\[引用内容\]:|\s*$)/s', $text, $matches);
        
        $quotes = [];
        if (!empty($matches[1])) {
            foreach ($matches[1] as $quote) {
                $quotes[] = trim($quote);
            }
        }
        
        // 移除引用内容，获取纯文本
        $cleanText = preg_replace('/\[引用内容\]:\s*.+?(?=\[引用内容\]:|$)/s', '', $text);
        $cleanText = trim($cleanText);
        
        return [
            'original_text' => $text,
            'clean_text' => $cleanText,
            'quotes' => $quotes
        ];
    }
    public function addData(Request $request)
    {
        // 记录日志（保持原有）
        $allParameters = $request->all();
        $timestamp = now()->toDateTimeString();

        $logContent = "=== 请求记录 ===\n";
        $logContent .= "时间: {$timestamp}\n";
        $logContent .= "方法: {$request->method()}\n";
        $logContent .= "URL: {$request->fullUrl()}\n";
        $logContent .= "参数:\n";

        foreach ($allParameters as $key => $value) {
            if (is_array($value)) {
                $value = json_encode($value, JSON_UNESCAPED_UNICODE);
            }
            $logContent .= "  {$key}: {$value}\n";
        }
        $logContent .= "================\n\n";

        Storage::disk('local')->append('request_logs/' . date('Y-m-d') . '.txt', $logContent);

        // 获取基本参数
        $avatar = $request->input('avatar');
        $user_id = $request->input('user_id');
        $nickname = $request->input('nickname');
        $publish_time = $request->input('publish_time');
        $article_id = $request->input('article_id');
        $images = $request->input('images', []);
        $has_retweet = $request->input('has_retweet', 0);
        $retweeted_content = $request->input('retweeted_content', '');

        // 处理 content 字段
        $content_input = $request->input('content', '[]');


        ##测试
/*        $testData1 = [
            'avatar' => 'https://example.com/avatar.jpg',
            'user_id' => '123456',
            'nickname' => '测试用户',
            'publish_time' => '2025-10-21 10:00:00',
            'article_id'=>'1234',
            'has_retweet'=>'0',
            'images'=>[
                '1.jpg',
                '2.jpg'
            ],
            'content' => json_encode([
                [
                    'type' => 'text', 
                    'text' => '这是纯文本内容'
                ],
                [
                    'type' => 'link',
                    'text' => 'https://p.pinduoduo.com/lXztwnXP?sc=EFAC',
                    'link_text' => '网页链接'
                ]
            ], JSON_UNESCAPED_UNICODE)
        ];

       

        $avatar = $testData1['avatar'];
        $user_id = $testData1['user_id'];
        $nickname = $testData1['nickname'];
        $publish_time = $testData1['publish_time'];
        $article_id = $testData1['article_id'];
        $images = $testData1['images'];
        $has_retweet = $testData1['has_retweet'];
        
        // 处理 content 字段
        $content_input = $testData1['content'];
*/
        ##测试




        $content_data = is_string($content_input) ? json_decode($content_input, true) ?? [] : $content_input;

        // 处理时间
        $publish_time_formatted = Carbon::parse($publish_time)->format('Y-m-d H:i:s');

        // 处理转发内容
        $processed_retweeted_content = [];
        if (!empty($retweeted_content) && $has_retweet == 1) {
            // 如果 retweeted_content 是 JSON 字符串，先解码
            if (is_string($retweeted_content)) {
                $retweeted_data = json_decode($retweeted_content, true) ?? [];
            } else {
                $retweeted_data = $retweeted_content;
            }
            
            if (!empty($retweeted_data)) {
                // 处理转发内容的文本
                $retweeted_text = '';
                $retweeted_processed_content = [];
                
                if (isset($retweeted_data['content']) && is_array($retweeted_data['content'])) {
                    foreach ($retweeted_data['content'] as $item) {
                        if (isset($item['type']) && $item['type'] === 'text' && !empty($item['text'])) {
                            $text_content = $item['text'];
                            $retweeted_text .= $text_content . "\n";
                            //dd($retweeted_text);
                            
                            // URL检测和处理（与主内容相同的逻辑）
                            if (preg_match('/^https?:\/\/[^\s]+$/', $text_content)) {
                                // 纯URL链接
                                $dat = ['shop_buy_url' => $text_content];
                                $resultdata = $this->pythonService->SmzdmLianJieJieXi($request, $dat, $is_zdm = false);
                                
                                if (!empty($resultdata['result'][0]['platform'])) {
                                    $retweeted_processed_content[] = [
                                        "type" => "link2",
                                        "text" => $text_content,
                                        "platform" => $resultdata['result']['0']['platform'],
                                        "product_id" => $resultdata['result']['0']['product_id'] ?? '',
                                        "link_text" => "网页链接",
                                    ];
                                } else {
                                    $retweeted_processed_content[] = [
                                        "type" => "link",
                                        "text" => $text_content,
                                        "link_text" => "网页链接",
                                    ];
                                }
                            } elseif (preg_match('/(https?:\/\/[^\s]+)/', $text_content, $matches)) {
                                // 文本中包含URL
                                $url = $matches[1];
                                $text_before = str_replace($url, '', $text_content);
                                
                                if (!empty(trim($text_before))) {
                                    $retweeted_processed_content[] = [
                                        "type" => "text",
                                        "text" => trim($text_before),
                                    ];
                                }
                                
                                $dat = ['shop_buy_url' => $url];
                                $resultdata = $this->pythonService->SmzdmLianJieJieXi($request, $dat, $is_zdm = false);
                                
                                if (!empty($resultdata['result'][0]['platform'])) {
                                    $retweeted_processed_content[] = [
                                        "type" => "link2",
                                        "text" => $url,
                                        "platform" => $resultdata['result']['0']['platform'],
                                        "product_id" => $resultdata['result']['0']['product_id'] ?? '',
                                        "link_text" => "网页链接",
                                    ];
                                } else {
                                    $retweeted_processed_content[] = [
                                        "type" => "link",
                                        "text" => $url,
                                        "link_text" => "网页链接",
                                    ];
                                }
                            } else {
                                // 纯文本
                                $retweeted_processed_content[] = [
                                    "type" => "text",
                                    "text" => $text_content,
                                ];
                            }
                        }
                    }
                }
                
                // 构建处理后的转发内容
                $processed_retweeted_content = [
                    'avatar' => $retweeted_data['avatar'] ?? '',
                    'user_id' => $retweeted_data['user_id'] ?? '',
                    'nickname' => $retweeted_data['nickname'] ?? '',
                    'publish_time' => $retweeted_data['publish_time'] ?? '',
                    'article_id' => $retweeted_data['article_id'] ?? '',
                    'content' => $retweeted_processed_content,
                    'images' => $retweeted_data['images'] ?? [],
                    'has_retweet' => $retweeted_data['has_retweet'] ?? 0,
                    'text' => trim($retweeted_text),
                ];
            }
        }

        // 处理主内容转换（简化版URL检测）
        $processed_content = [];
        $text = '';

        if (!empty($content_data)) {
            foreach ($content_data as $item) {
                if (isset($item['type'])) {
                    if ($item['type'] === 'text' && !empty($item['text'])) {
                        $text_content = $item['text'];
                        $text .= $text_content . "\n";
                        
                        //echo ($text_content);
                        // 检测是否是URL链接
                        if (preg_match('/^https?:\/\/[^\s]+$/', $text_content)) {
                            // 是URL链接，进行解析
                            $dat = ['shop_buy_url' => $text_content];
                            //dd($dat);
                            $resultdata = $this->pythonService->SmzdmLianJieJieXi($request, $dat, $is_zdm = false);
                            
                            if (!empty($resultdata['result'][0]['platform'])) {
                                $processed_content[] = [
                                    "type" => "link2",
                                    "text" => $text_content,
                                    "platform" => $resultdata['result']['0']['platform'],
                                    "product_id" => $resultdata['result']['0']['product_id'] ?? '',
                                    "link_text" => "网页链接",
                                ];
                            } else {
                                $processed_content[] = [
                                    "type" => "link",
                                    "text" => $text_content,
                                    "link_text" => "网页链接",
                                ];
                            }
                        } else {
                            // 不是URL，检查文本中是否包含URL
                            if (preg_match('/(https?:\/\/[^\s]+)/', $text_content, $matches)) {
                                $url = $matches[1];
                                // 先添加URL前的文本
                                $text_before = str_replace($url, '', $text_content);
                                if (!empty(trim($text_before))) {
                                    $processed_content[] = [
                                        "type" => "text",
                                        "text" => trim($text_before),
                                    ];
                                }
                                
                                // 添加URL链接
                                $dat = ['shop_buy_url' => $url];
                                $resultdata = $this->pythonService->SmzdmLianJieJieXi($request, $dat, $is_zdm = false);
                                
                                if (!empty($resultdata['result'][0]['platform'])) {
                                    $processed_content[] = [
                                        "type" => "link2",
                                        "text" => $url,
                                        "platform" => $resultdata['result']['0']['platform'],
                                        "product_id" => $resultdata['result']['0']['product_id'] ?? '',
                                        "link_text" => "网页链接",
                                    ];
                                } else {
                                    $processed_content[] = [
                                        "type" => "link",
                                        "text" => $url,
                                        "link_text" => "网页链接",
                                    ];
                                }
                            } else {
                                // 纯文本
                                $processed_content[] = [
                                    "type" => "text",
                                    "text" => $text_content,
                                ];
                            }
                        }
                        
                    } elseif ($item['type'] === 'link' && !empty($item['text'])) {
                        // 直接就是链接类型
                        $url = $item['text'];
                        $text .= $url . "\n";
                        $dat = ['shop_buy_url' => $url];
                        //dd($dat);
                        $resultdata = $this->pythonService->SmzdmLianJieJieXi($request, $dat, $is_zdm = false);

                        
                        if (!empty($resultdata['result'][0]['platform'])) {
                            $processed_content[] = [
                                "type" => "link2",
                                "text" => $url,
                                "platform" => $resultdata['result']['0']['platform'],
                                "product_id" => $resultdata['result']['0']['product_id'] ?? '',
                                "link_text" => $item['link_text'] ?? '网页链接',
                            ];
                        } else {
                            $processed_content[] = [
                                "type" => "link",
                                "text" => $url,
                                "link_text" => $item['link_text'] ?? '网页链接',
                            ];
                        }
                    }
                }
            }
        }

        // 准备数据
        $data = [];
        $data['processed_content'] = $processed_content;
        $data['images'] = $images;
        $data['retweeted_content'] = $processed_retweeted_content;

        // 确保数组字段不为空
        if (empty($data['images'])) {
            $data['images'] = [];
        }
        $data['images'] = json_encode($data['images'], JSON_UNESCAPED_UNICODE);

        if (empty($data['processed_content'])) {
            $data['processed_content'] = [];
        }
        $data['processed_content'] = json_encode($data['processed_content'], JSON_UNESCAPED_UNICODE);

        if (empty($data['retweeted_content'])) {
            $data['retweeted_content'] = [];
        }
        $data['retweeted_content'] = json_encode($data['retweeted_content'], JSON_UNESCAPED_UNICODE);

        // 构建最终数据
        $datas = [
            'unique_id' => $article_id,
            'avatar' => $avatar,
            'images' => $data['images'],
            'nickname' => $nickname,
            'uid' => $user_id,
            'user_id' => $user_id,
            'article_id' => $article_id,
            'has_retweet' => $has_retweet,
            'publish_time' => $publish_time_formatted,
            'created_at' => $publish_time,
            'content' => $data['processed_content'],
            'product_num' => $request->input('product_num', 0),
            'retweeted_content' => $data['retweeted_content'],
            'is_weibo_chaohua' => $request->input('is_weibo_chaohua', 0),
            'article_detail_url' => $request->input('article_detail_url', ''),
        ];
        //dd($datas);

        //return $this->success($this->repository->addData($request, $datas));
    }
    public function addData444(Request $request)
    {
        // 记录日志（保持原有）
        $allParameters = $request->all();
        $timestamp = now()->toDateTimeString();

        $logContent = "=== 请求记录 ===\n";
        $logContent .= "时间: {$timestamp}\n";
        $logContent .= "方法: {$request->method()}\n";
        $logContent .= "URL: {$request->fullUrl()}\n";
        $logContent .= "参数:\n";

        foreach ($allParameters as $key => $value) {
            if (is_array($value)) {
                $value = json_encode($value, JSON_UNESCAPED_UNICODE);
            }
            $logContent .= "  {$key}: {$value}\n";
        }
        $logContent .= "================\n\n";

        Storage::disk('local')->append('request_logs/' . date('Y-m-d') . '.txt', $logContent);

        // 获取基本参数
        $avatar = $request->input('avatar');
        $user_id = $request->input('user_id');
        $nickname = $request->input('nickname');
        $publish_time = $request->input('publish_time');
        $article_id = $request->input('article_id');
        $images = $request->input('images', []);
        $has_retweet = $request->input('has_retweet', 0);
        $retweeted_content=$request->input('retweeted_content', 0);
        // 处理 content 字段
        $content_input = $request->input('content', '[]');

        ##测试
        /*$testData1 = [
            'avatar' => 'https://example.com/avatar.jpg',
            'user_id' => '123456',
            'nickname' => '测试用户',
            'publish_time' => '2025-10-21 10:00:00',
            'article_id'=>'1234',
            'has_retweet'=>'0',
            'images'=>[
                '1.jpg',
                '2.jpg'
            ],
            'content' => json_encode([
                ['type' => 'text', 'text' => '这是纯文本内容'],
                ['type' => 'text', 'text' => '没有链接'],
            ])
        ];

        $avatar = $testData1['avatar'];
        $user_id = $testData1['user_id'];
        $nickname = $testData1['nickname'];
        $publish_time = $testData1['publish_time'];
        $article_id = $testData1['article_id'];
        $images = $testData1['images'];
        $has_retweet = $testData1['has_retweet'];
        
        // 处理 content 字段
        $content_input = $testData1['content'];
*/
        ##测试



        $content_data = is_string($content_input) ? json_decode($content_input, true) ?? [] : $content_input;
        
        // 处理时间
        $publish_time_formatted = Carbon::parse($publish_time)->format('Y-m-d H:i:s');

        ##超话内容处理一遍

        if($retweeted_content==1){


        }

        //dd($publish_time_formatted);
        
        // 处理内容转换（简化版URL检测）
        $processed_content = [];
        $text = '';
        
        if (!empty($content_data)) {
            foreach ($content_data as $item) {
                if (isset($item['type'])) {
                    if ($item['type'] === 'text' && !empty($item['text'])) {
                        $text_content = $item['text'];
                        $text .= $text_content . "\n";
                        
                        // 检测是否是URL链接
                        if (preg_match('/^https?:\/\/[^\s]+$/', $text_content)) {
                            // 是URL链接，进行解析
                            $dat = ['shop_buy_url' => $text_content];
                            $resultdata = $this->pythonService->SmzdmLianJieJieXi($request, $dat, $is_zdm = false);
                            
                            if (!empty($resultdata['result'][0]['platform'])) {
                                $processed_content[] = [
                                    "type" => "link2",
                                    "text" => $text_content,
                                    "platform" => $resultdata['result']['0']['platform'],
                                    "product_id" => $resultdata['result']['0']['product_id'] ?? '',
                                    "link_text" => "网页链接",
                                ];
                            } else {
                                $processed_content[] = [
                                    "type" => "link",
                                    "text" => $text_content,
                                    "link_text" => "网页链接",
                                ];
                            }
                        } else {
                            // 不是URL，检查文本中是否包含URL
                            if (preg_match('/(https?:\/\/[^\s]+)/', $text_content, $matches)) {
                                $url = $matches[1];
                                // 先添加URL前的文本
                                $text_before = str_replace($url, '', $text_content);
                                if (!empty(trim($text_before))) {
                                    $processed_content[] = [
                                        "type" => "text",
                                        "text" => trim($text_before),
                                    ];
                                }
                                
                                // 添加URL链接
                                $dat = ['shop_buy_url' => $url];
                                $resultdata = $this->pythonService->SmzdmLianJieJieXi($request, $dat, $is_zdm = false);
                                
                                if (!empty($resultdata['result'][0]['platform'])) {
                                    $processed_content[] = [
                                        "type" => "link2",
                                        "text" => $url,
                                        "platform" => $resultdata['result']['0']['platform'],
                                        "product_id" => $resultdata['result']['0']['product_id'] ?? '',
                                        "link_text" => "网页链接",
                                    ];
                                } else {
                                    $processed_content[] = [
                                        "type" => "link",
                                        "text" => $url,
                                        "link_text" => "网页链接",
                                    ];
                                }
                            } else {
                                // 纯文本
                                $processed_content[] = [
                                    "type" => "text",
                                    "text" => $text_content,
                                ];
                            }
                        }
                        
                    } elseif ($item['type'] === 'link' && !empty($item['text'])) {
                        // 直接就是链接类型
                        $url = $item['text'];
                        $text .= $url . "\n";
                        
                        $dat = ['shop_buy_url' => $url];
                        $resultdata = $this->pythonService->SmzdmLianJieJieXi($request, $dat, $is_zdm = false);
                        
                        if (!empty($resultdata['result'][0]['platform'])) {
                            $processed_content[] = [
                                "type" => "link2",
                                "text" => $url,
                                "platform" => $resultdata['result']['0']['platform'],
                                "product_id" => $resultdata['result']['0']['product_id'] ?? '',
                                "link_text" => $item['link_text'] ?? '网页链接',
                            ];
                        } else {
                            $processed_content[] = [
                                "type" => "link",
                                "text" => $url,
                                "link_text" => $item['link_text'] ?? '网页链接',
                            ];
                        }
                    }
                }
            }
        }
        //dd($processed_content);
        $data['processed_content']=$processed_content;
        //dd($data['retweeted_content']);
        $data['images']=$images;
        $data['retweeted_content']=$retweeted_content;

        if(!isset($data['images']) || empty($data['images'])){
            $data['images']=[];
        }
        $data['images'] = json_encode($data['images'], JSON_UNESCAPED_UNICODE);

        if(!isset($data['processed_content']) || empty($data['processed_content'])){
            $data['processed_content']=[];
        }
        $data['processed_content'] = json_encode($data['processed_content'], JSON_UNESCAPED_UNICODE);


        if(!isset($data['retweeted_content'])|| empty($data['retweeted_content'])){
            $data['retweeted_content']=[];
        }
        $data['retweeted_content'] = json_encode($data['retweeted_content'], JSON_UNESCAPED_UNICODE);

        if(!isset($data['comments'])|| empty($data['comments'])){
            $data['comments']=[];
        }
        $data['comments'] = json_encode($data['comments'], JSON_UNESCAPED_UNICODE);


        
        $datas = [
            'unique_id'=>$article_id,
            'avatar' => $avatar,
            'images' => $data['images'],
            'nickname' => $nickname,
            'uid' => $user_id,
            'user_id' => $user_id,
            'article_id' => $article_id,
            'has_retweet' => $has_retweet,
            'publish_time' => $publish_time_formatted,
            'created_at' => $publish_time,
            'content' => $data['processed_content'],
            'product_num' => $request->input('product_num', 0),
            'retweeted_content'=>$data['retweeted_content'],
            'is_weibo_chaohua'=>$request->input('is_weibo_chaohua', 0),
            'article_detail_url'=>$request->input('article_detail_url', 0),
        ];

        //dd($datas);

        return $this->success($this->repository->addData($request, $datas));
    }


    

  

}
